// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// G [author] rhyme_lph
// E [email]  rhymelph@gmail.com
// f [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:dio/src/response.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/entities/business_contact_entity.dart';
import 'package:finance_app/src/http_service/http_contact_service.dart';
import 'package:finance_app/src/http_service/http_dashboard_service.dart';
import 'package:finance_app/src/mixin/format_group_map_mixin.dart';
import 'package:finance_app/src/mixin/refresh_mixin.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/widgets/bottom_sheet/sort_contact_bottom_sheet.dart';

class DashboardContactsProvider
    extends BaseProvider<List<BusinessContactEntity>>
    with
        FormatGroupMapLocalMixin<BusinessContactEntity>,
        RefreshMixin<List<BusinessContactEntity>, List<BusinessContactEntity>> {
  String currentSelectSortContact;
  List<BusinessContactEntity> dataList;

  void onSelectSortContact() {
    obtainContext?.call((context) async {
      currentSelectSortContact =
          await showSortContactBottomSheet(context, currentSelectSortContact);
      contactToMap(dataList);
      update();
    });
  }

  @override
  void initState() {
    currentSelectSortContact = S.current.alphabetical;
    super.initState();
    _loadData();
  }

  Future<void> _loadData() async {
    await post(HttpDashboardService.dashboardContacts(1), onSuccess: (result) {
      dataList = getEntityFromResult<List<BusinessContactEntity>>(result);
      contactToMap(dataList);
      update();
    });
  }

  void contactToMap(List<BusinessContactEntity> contacts) {
    groupMap.clear();
    if (currentSelectSortContact == S.current.alphabetical) {
      sortGroupToMap(contacts,
          sort: (a, b) => sortNameFirst(a, b, (t) => t.name),
          group: (a) => groupFirstName(a, (t) => t.name, '*'),
          itemBefore: (map, b) => favoriteBefore(map, b, (b) => b.isFavorite));
      if (groupMap['Favourites'] != null &&
          groupMap['Favourites'].length == 0) {
        groupMap.remove('Favourites');
      }
    } else if (currentSelectSortContact == S.current.recently_transacted) {
      sortGroupToMap(contacts,
          sort: (a, b) =>
              sortIssuesAt(a, b, (t) => t.lastTransactionAt, (t) => t.id),
          group: (a) => groupMonth(a, (t) => t.lastTransactionAt));
    } else {
      sortGroupToMap(contacts,
          sort: (a, b) => sortPayAmount(a, b, (t) => t.isFavorite,
              (t) => (t.receivingAmount ?? 0.0) - (t.payingAmount ?? 0.0)),
          group: groupOnly);
    }
  }

  @override
  Future get dataFuture => null;

  void onNavViewAll() {
    Routes.navigateTo(RouterGenProviders.allContactsPage);
    // Routes.navigateTo(RouterGenProviders.mainBusinessContactPage);
  }

  void onNavContactDetail(BusinessContactEntity e) async {
    var result = await Routes.navigateTo(
        RouterGenProviders.businessContactDetailPage,
        params: {
          'data': e,
        });

    print(result);
  }

  void onClickStar(BusinessContactEntity e) async {
    bool isSuccess = false;
    await post(
        HttpContactService.updateContact(e.id,
            is_favorite: e.isFavorite == 1 ? 0 : 1),
        autoHandler: AutoHandler.Toast,
        loadingTip: S.current.loading, onSuccess: (result) {
      isSuccess = true;
    });
    if (isSuccess == true) {
      e.isFavorite = e.isFavorite == 1 ? 0 : 1;
      contactToMap(dataList);
      update();
    }
  }

  @override
  Future get refreshFuture => HttpDashboardService.dashboardContacts(1);

  @override
  List<BusinessContactEntity> getFromRequestResult(
      Response result, bool isRefresh) {
    final list = getEntityFromResult<List<BusinessContactEntity>>(result);

    contactToMap(list);
    return list;
  }
}
